<template>
    <v-container>

        <h4 class="mb-3">常见问题管理</h4>

        <v-row>
            <v-col>
                 <v-text-field v-model="title" placeholder="标题"></v-text-field>
            </v-col>
            <v-col cols="2">
                <v-text-field v-model="order" hint="数字越大越靠后" persistent-hint label="排序"></v-text-field>
            </v-col>
        </v-row>
        <Tiptap v-model="content"></Tiptap>
        <v-divider class="mb-4"></v-divider>
        <v-row dense no-gutters>
            <v-col>
                <v-btn depressed color="primary" class="mr-2" @click="save" :loading="saving">保存</v-btn>
            </v-col>
        </v-row>

    </v-container>
</template>

<script>
    import axios from "axios";
    import Tiptap from "../../../widgets/Tiptap.vue";

    export default {
        data: () => ({
            title: '',
            content: '',
            order: 999,
            saving: false
        }),

        components: {
            Tiptap,
        },

        created() {
            this.id = this.$route.params.id ? parseInt(this.$route.params.id) : 0;
            this.load();
        },

        beforeRouteUpdate(to, from, next) {
            this.id = to.params.id ? parseInt(to.params.id) : 0;
            this.load();
            next();
        },

        methods: {
            load() {
                if (this.id <= 0) return;

                axios.get(`/app/qa/${this.id}`).then((response) => {
                    if(response.data.code == 0) {
                        this.title = response.data.data ?  response.data.data.title : '';
                        this.content = response.data.data ?  response.data.data.content : '';
                    }
                })
                .catch(function () {})
                .then(function () {
                });
            },

            save() {
                this.saving = true;
                const that = this;
                const url = this.id > 0 ? `/app/qa/${this.id}` : `/app/qa`;
                axios.post(url, {title: this.title, content: this.content, order: this.order}).then((response) => {
                    if (this.id == 0 &&  response.data.code == 0) {
                        this.$router.push({
                            path: `/app/qa/edit/${response.data.data.id}`
                        });
                    }

                    this.$toast.open({
                        message: response.data.msg,
                        type: response.data.code == 0 ? 'success' : 'error',
                        position: 'top-right',
                    });
                })
                .catch(function () {})
                .then(function () {
                    that.saving = false;
                });
            }
        }
    }
</script>